package com.aiyige.utils.removal.dao;

import android.util.Log;

import com.aiyige.MyApp;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.removal.ReDBHelper;
import com.aiyige.utils.removal.RemovalHandler;
import com.aiyige.utils.removal.entity.CacheTaskEntity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 缓存任务
 * Created by UQIANTU on 16/11/23.
 */

public class CacheTaskDao {

    private static CacheTaskDao instance = null;

    private Dao<CacheTaskEntity, Integer> dao;
    private ReDBHelper dbHelper;

    public static synchronized CacheTaskDao getInstance() {
        if (instance == null) {
            instance = new CacheTaskDao();
        }
        return instance;
    }

    public CacheTaskDao() {
        init();
    }

    public void init() {
        dbHelper = ReDBHelper.getHelper(MyApp.getAppContext());
        dao = dbHelper.getDao(CacheTaskEntity.class);
    }

    int p = 0;

    /**
     * 添加缓存任务
     *
     * @param info
     */
    public synchronized void addCache(CacheTaskEntity info) {
        try {
            p++;
            List<CacheTaskEntity> list = dao.queryForEq("serverCode", info.getServerCode() != null ? info.getServerCode() : "");
            if (list == null || list.isEmpty()) {
                dao.create(info);
                Log.e("xcxcxc", "添加缓存任务:" + p);
            } else {
                Log.e("xcxcxc", "添加缓存任务有重复了！！！！:" + p);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否已缓存
     *
     * @param info
     * @return
     */
    public boolean isHasCached(CacheTaskEntity info) {
        return isHasCached(info.getServerCode());
    }

    public boolean isHasCached(String serverCode) {
        try {
            List<CacheTaskEntity> list = dao.queryForEq("serverCode", serverCode);
            if (null != list && !list.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 更新缓存
     *
     * @param info
     */
    public void updateCache(CacheTaskEntity info) {
        if (info.getLocalId() == 0) {
            CacheTaskEntity cache = find(info.getServerCode());
            if (null != cache) {
                info.setLocalId(cache.getLocalId());
            } else {
                addCache(info);
                return;
            }
        }
        try {
            dao.update(info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据ServerCode删除
     *
     * @param serverCodeList
     */
    public int deleteServerCodeByUserId(List<String> serverCodeList) {
        if (ListUtil.isEmpty(serverCodeList)) {
            return 0;
        }
        String userId = AccountUtil.getCurrentUser().getId();
        int successCount = 0;
        for (String serverCode : serverCodeList) {
            try {
                DeleteBuilder<CacheTaskEntity, Integer> deleteBuilder = dao.deleteBuilder();
                if (RemovalHandler.isDebug) {
                    deleteBuilder.where().eq("serverCode", serverCode);
                } else {
                    deleteBuilder.where().eq("serverCode", serverCode)
                            .and().eq("userId", userId);
                }

                int success = deleteBuilder.delete();
                if (success > 0) {
                    successCount++;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return successCount;
    }


    public CacheTaskEntity find(String serverCode) {
        try {
            List<CacheTaskEntity> list = dao.queryForEq("serverCode", serverCode);
            if (null != list && !list.isEmpty()) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询缓存
     *
     * @param typeId 0代表看,1代表学
     * @return
     */
    public List<CacheTaskEntity> queryCaches(int typeId) {
        List<CacheTaskEntity> list = new ArrayList<>();

        try {
            List<CacheTaskEntity> data = dao.queryBuilder().orderBy("createTime", false).where().eq("typeId", typeId).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询缓存(根据UserId查询)
     *
     * @param
     * @return 未登录则返回空
     */
    public List<CacheTaskEntity> queryAllCachesByUserId() {
        if (!LoginManager.getInstance().isLogin()) {
            return null;
        }
        String userId = AccountUtil.getCurrentUser().getId();
        List<CacheTaskEntity> list = new ArrayList<>();
        List<CacheTaskEntity> data;
        try {
            if (RemovalHandler.isDebug) {
                data = dao.queryBuilder()
                        .orderBy("createTime", false)
                        .query();
            } else {
                data = dao.queryBuilder().
                        orderBy("createTime", false)
                        .where().eq("userId", userId)
                        .query();
            }
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询未下载完的缓存
     *
     * @return
     */
    public List<CacheTaskEntity> queryUnDownloadCache() {
        List<CacheTaskEntity> list = new ArrayList<>();
        try {
            List<CacheTaskEntity> data = dao.queryBuilder().where().eq("status", CacheTaskEntity.STATUS_WAIT_DOWNLOAD).or().eq("status", CacheTaskEntity.STATUS_PAUSE).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询已下载完的缓存
     *
     * @return
     */
    public List<CacheTaskEntity> queryDownloadedCache() {
        List<CacheTaskEntity> list = new ArrayList<>();
        try {
            List<CacheTaskEntity> data = dao.queryBuilder().where().eq("status", CacheTaskEntity.STATUS_FINISHED).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询缓存状态
     *
     * @param serverCode
     * @return
     */
    public boolean queryCacheStatus(String serverCode) {
        try {
            List<CacheTaskEntity> list = dao.queryForEq("serverCode", serverCode);
            if (null != list && !list.isEmpty()) {
                return (list.get(0).getStatus() == CacheTaskEntity.STATUS_FINISHED);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询缓存状态
     *
     * @param serverCode
     * @return
     */
    public CacheTaskEntity queryCacheEntity(String serverCode) {
        try {
            List<CacheTaskEntity> list = dao.queryForEq("serverCode", serverCode);
            if (null != list && !list.isEmpty()) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取缓存总数
     *
     * @return
     */
    public int getCacheCount() {
        int count = 0;
        try {
            count = Long.valueOf(dao.countOf()).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}